// pages/articleDetails/articleDetails.js
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */

  data: {
    momentId: null, //瞬间标识id
    showCollect: true, //true  显示空白  false  显示实心
    collectList: null,
    showGuanzhu: true, //true  显示关注  false  显示取消关注
    followList: null,
    buttonType: 'default', //点赞按钮样式类别
    momentCommentCount: '0', //总评论数
    article: '', //富文本  单独拿出来
    sysMoment: null, //瞬间的详情
    sysMomentFiles: [], //图片列表
    sysMomentComments: [], //一级评论列表
    momentCount: 0,
    // 推荐商品
    recommend: [{
        title: '论有温度的家，我只服这家装修',
        aythor: '最美改造家',
        time: '18分钟前',
        zan: '3210',
        img: ['http://m.qpic.cn/psc?/V11Sie321T6lY9/OmVq1gFIObiZCCY30a7VN8CrSyZQ2rlRVp3vB5xlf5o23CHAiNJIrUhRTJzbQmwp3geLaSuwtKUoYe3KIkRl7w!!/b&bo=*wD*AP8A*wADCSw!&rf=viewer_4', 'http://m.qpic.cn/psc?/V11Sie321T6lY9/LjNfElrpEt6hXz54k3bCMbmH3j1WHNErlkkehAq3vu4dpHnzv9ddNVb4MS.eC95NjdqdBtiP0Z251TocsE.tV4lepNUvkY6VjcX0alP4cjY!/b&bo=*wD*AP8A*wADGTw!&rf=viewer_4', 'http://m.qpic.cn/psc?/V11Sie321T6lY9/LjNfElrpEt6hXz54k3bCMc*InXBbk*rp2V3s1ZzZbOpY37Ljasqj27qcNBLBGrtvThAUENB5LOr0NZguCmSPZMLul9UOb18EzjT97aBnN.0!/b&bo=*wD*AP8A*wADGTw!&rf=viewer_4']
      },
      {
        title: '房子装修，现在客厅流行这么装，沙发不靠墙 7种设计方案',
        aythor: '飞翔的企鹅',
        time: '一小时前',
        zan: '4423',
        img: ['http://m.qpic.cn/psc?/V11Sie321T6lY9/OmVq1gFIObiZCCY30a7VN8CrSyZQ2rlRVp3vB5xlf5o23CHAiNJIrUhRTJzbQmwp3geLaSuwtKUoYe3KIkRl7w!!/b&bo=*wD*AP8A*wADCSw!&rf=viewer_4', 'http://m.qpic.cn/psc?/V11Sie321T6lY9/LjNfElrpEt6hXz54k3bCMbmH3j1WHNErlkkehAq3vu4dpHnzv9ddNVb4MS.eC95NjdqdBtiP0Z251TocsE.tV4lepNUvkY6VjcX0alP4cjY!/b&bo=*wD*AP8A*wADGTw!&rf=viewer_4', 'http://m.qpic.cn/psc?/V11Sie321T6lY9/LjNfElrpEt6hXz54k3bCMc*InXBbk*rp2V3s1ZzZbOpY37Ljasqj27qcNBLBGrtvThAUENB5LOr0NZguCmSPZMLul9UOb18EzjT97aBnN.0!/b&bo=*wD*AP8A*wADGTw!&rf=viewer_4']
      }
    ]
  },
  //获取评论信息
  getComment() {
    // var postObj = {
    //   url: `/mobileUser/comment`,
    //   method: 'get'
    // }
    // app.request.loginRequest(postObj).then(res => {
    //   if (res.data.code === 200) {
    //     console.log('获取评论信息', res)

    //   }
    // })
  },
  // 获取富文本  和一级评论
  getRich(id) {
    wx.showLoading({
      title: '加载中...',
    })
    var postObj = {
      url: `/mobileUser/moment/getMomentInfo/${id}`,
      method: 'get'
    }
    app.request.loginRequest(postObj).then(res => {
      wx.hideLoading()
      if (res.data.code === 200) {
        console.log('获取', res)
        var rich = res.data.data.sysMoment.detail
        rich = app.util.formatRichText(rich)

        res.data.data.sysMoment.sysUser.avatar = app.util.config().api + res.data.data.sysMoment.sysUser.avatar
        if (!!res.data.data.sysMoment.videoUrl) {
          res.data.data.sysMoment.videoUrl = app.util.config().api + res.data.data.sysMoment.videoUrl
        }
        if (res.data.data.sysMomentFiles.length > 0) {
          res.data.data.sysMomentFiles.forEach((items, i) => {
            items.url = app.util.config().api + items.url
          })
        }


        if (res.data.data.sysMomentComments.length > 0) {
          res.data.data.sysMomentComments.forEach((items, i) => {
            items.sysMobileUser.image = app.util.config().api + items.sysMobileUser.image
            items.isZan = false //判断点赞
          })
        }

        this.setData({
          article: rich,
          sysMoment: res.data.data.sysMoment,
          sysMomentFiles: res.data.data.sysMomentFiles,
          sysMomentComments: res.data.data.sysMomentComments,
          momentCount: res.data.data.momentCount,
          momentCommentCount: res.data.data.momentCommentCount
        })
        if (app.globalData.hasLogin == true) {
          this.checkcommentListZan()
          this.followList()
          this.collectList()
        }

      }
    })
  },
  // 检验文章是否点赞
  checkParise() {
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/parise/list`,
        method: 'get',
        data: {
          momentId: this.data.momentId
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          // console.log('检验是否点赞', res)
          if (res.data.data.momentList.length == 0) {
            this.parise()
          } else {
            this.removeParise()
          }

        }
      })
    }
  },
  //文章点赞
  parise() {
    // app.checkHasLogin()
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/parise`,
        method: 'post',
        data: {
          momentId: this.data.momentId
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          console.log('点赞', res)
          wx.showToast({
            title: '点赞成功',
            image: '../../assets/success.png',
            duration: 1000,
            mask: true
          })
          this.setData({
            buttonType: 'info',
            momentCount: +this.data.momentCount + 1
          })

          var postObj = {
            url: `/mobileUser/parise/list`,
            method: 'get',
            data: {
              momentId: this.data.momentId
            }
          }
          app.request.wxRequest(postObj).then(res => {
            if (res.data.code === 200) {
              console.log('检验是否点赞', res)
              if (res.data.data.momentList.length == 0) {
                this.setData({
                  buttonType: 'default'
                })
              } else {
                this.setData({
                  buttonType: 'info'
                })
              }
            }
          })

          // this.getRich(this.data.momentId)
        }
      })
    }
  },
  //文章 取消点赞
  removeParise() {
    var postObj = {
      url: `/mobileUser/parise/remove`,
      method: 'delete',
      data: {
        momentId: this.data.momentId
      }
    }
    app.request.wxRequest(postObj).then(res => {
      if (res.data.code === 200) {
        wx.showToast({
          title: '取消成功',
          image: '../../assets/success.png',
          duration: 1000,
          mask: true
        })
        this.setData({
          buttonType: 'default',
          momentCount: (+this.data.momentCount - 1 <= 0) ? 0 : (+this.data.momentCount - 1)
        })

        var postObj = {
          url: `/mobileUser/parise/list`,
          method: 'get',
          data: {
            momentId: this.data.momentId
          }
        }
        app.request.wxRequest(postObj).then(res => {
          if (res.data.code === 200) {
            console.log('检验是否点赞', res)
            if (res.data.data.momentList.length == 0) {
              this.setData({
                buttonType: 'default'
              })
            } else {
              this.setData({
                buttonType: 'info'
              })
            }
          }
        })


        // this.getRich(this.data.momentId)
      }
    })
  },
  //写评论  评论文章，不需要parentCommentId  type=1
  toWrite() {
    if (app.checkHasLogin()) {
      wx.navigateTo({
        url: '/pages/find/releaseNews/releaseNews?type=1&momentId=' + this.data.momentId,
      })
    }
  },
  //commentItem   回复一级评论信息  
  commentItem(e) {
    var commentId = e.currentTarget.dataset.commentid
    if (app.checkHasLogin()) {
      wx.navigateTo({
        url: '/pages/find/releaseNews/releaseNews?type=2&commentId=' + commentId,
      })
    }

  },
  //  getCommentList   获取评论详情列表
  getCommentList(e) {
    var commentId = e.currentTarget.dataset.commentid
    var index = e.currentTarget.dataset.index

    var postObj = {
      url: `/mobileUser/comment/${commentId}`,
      method: 'get',
    }
    app.request.loginRequest(postObj).then(res => {
      if (res.data.code === 200) {
        console.log('获取评论详情列表', res)
        var sysMomentCommentList = res.data.data.sysMomentCommentList
        var sysMomentComments = this.data.sysMomentComments
        sysMomentComments[index].sysMomentCommentList = sysMomentCommentList
        this.setData({
          sysMomentComments: sysMomentComments
        })
      }
    })

  },
  //clearCommentList  收起评论详情
  clearCommentList(e) {
    var index = e.currentTarget.dataset.index
    var sysMomentComments = this.data.sysMomentComments

    delete sysMomentComments[index].sysMomentCommentList //true

    this.setData({
      sysMomentComments: sysMomentComments
    })
  },
  // 检验评论是否点赞
  checkcommentListZan() {
    var postObj = {
      url: `/mobileUser/parise/list`,
      method: 'get',
      data: {
        momentId: this.data.momentId
      }
    }

    // ////////////////////////////////////////
    app.request.wxRequest(postObj).then(res => {
      if (res.data.code === 200) {
        console.log('检验文章是否点赞', res.data.data);
        var momentCommentList = res.data.data.momentCommentList //已经点赞的
        var sysMomentComments = this.data.sysMomentComments //所有一级

        // if (momentCommentList.length > 0) {
        var arr = []
        momentCommentList.forEach((items1, i1) => {
          arr.push(items1['momentCommentId'])
        })
        // console.log(arr);
        sysMomentComments.forEach((items, i) => {
          var index = +arr.indexOf(items.commentId)
          // console.log(index);

          if (index === -1) {
            sysMomentComments[i].isZan = false
          } else {
            sysMomentComments[i].isZan = true
          }

          // console.log(sysMomentComments[i].isZan);

        })

        this.setData({
          sysMomentComments: sysMomentComments
        })
        // console.log(this.data.sysMomentComments);
        // }



      }
    })

  },
  // zanComment  点赞评论
  zanComment(e) {
    var commentId = e.currentTarget.dataset.commentid
    var index = e.currentTarget.dataset.index
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/parise`,
        method: 'post',
        data: {
          momentCommentId: commentId,
          // momentId: this.data.momentId
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '点赞成功',
            image: '../../assets/success.png',
            duration: 1000,
            mask: true
          })
          console.log('点赞评论成功', res)
          var sysMomentComments = this.data.sysMomentComments
          sysMomentComments[index].momentCommentPariseCount = res.data.data
          this.setData({
            sysMomentComments: sysMomentComments
          })
          this.checkcommentListZan()
        }
      })
    }
  },
  //deleteZanComment  取消点赞评论
  deleteZanComment(e) {
    var commentId = e.currentTarget.dataset.commentid
    var index = e.currentTarget.dataset.index
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/parise/remove`,
        method: 'delete',
        data: {
          momentCommentId: commentId,
          // momentId: this.data.momentId
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '取消成功',
            image: '../../assets/success.png',
            duration: 1000,
            mask: true
          })
          console.log('取消点赞评论', res)
          var sysMomentComments = this.data.sysMomentComments
          sysMomentComments[index].momentCommentPariseCount = res.data.data
          this.setData({
            sysMomentComments: sysMomentComments
          })
          this.checkcommentListZan()
        }
      })
    }
  },



  // 视频播放
  videoErrorCallback(e) {
    console.log('视频错误信息:')
    console.log(e.detail.errMsg)
  },
  bindVideoEnterPictureInPicture() {
    console.log('进入小窗模式')
  },
  bindVideoLeavePictureInPicture() {
    console.log('退出小窗模式')
  },


  //获取关注列表
  followList() {
    var postObj = {
      url: `/mobileUser/follow/list`,
      method: 'get'
    }
    app.request.wxRequest(postObj).then(res => {
      if (res.data.code === 200) {
        var userId = this.data.sysMoment.sysUser.userId
        console.log('获取关注列表', res)
        var followList = res.data.data
        for (let index = 0; index < followList.length; index++) {
          const element = followList[index];
          if (element.userId == userId) {
            this.setData({
              showGuanzhu: false
            })
            break;
          }
        }
        this.setData({
          followList: followList
        })
      }
    })
  },
  // 新增关注 POST/mobileUser/follow  
  followYes() {
    var userId = this.data.sysMoment.sysUser.userId
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/follow`,
        method: 'post',
        data: {
          userId: userId, //被关注人的id
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          console.log('新增关注', res)
          wx.showToast({
            title: '关注成功',
            image: '../../assets/success.png',
            duration: 1000,
          })
          this.setData({
            showGuanzhu: false
          })
          this.followList()
        }
      })
    }

  },
  // 删除关注 /mobileUser/follow/edit删除关注
  followNo() {
    var userId = this.data.sysMoment.sysUser.userId
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/follow/edit`,
        method: 'put',
        data: {
          userId: userId
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          console.log('取消关注成功', res)
          wx.showToast({
            title: '取消关注',
            image: '../../assets/success.png',
            duration: 1000,
          })
          this.setData({
            showGuanzhu: true
          })
          this.followList()
        }
      })
    }
  },



  //获取收藏平台瞬间 列表
  collectList() {
    var postObj = {
      url: `/mobileUser/collection/list`,
      method: 'get'
    }
    app.request.wxRequest(postObj).then(res => {
      if (res.data.code === 200) {
        var momentId = this.data.momentId
        console.log('收藏平台瞬间', res)
        var collectList = res.data.rows
        for (let index = 0; index < collectList.length; index++) {
          const element = collectList[index];
          if (element.momentId == momentId) {
            this.setData({
              showCollect: false
            })
            break;
          }
        }
        this.setData({
          collectList: collectList
        })
      }
    })
  },
  // 新增关注收藏平台瞬间  
  collectYes() {
    var momentId = this.data.momentId
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/collection`,
        method: 'post',
        data: {
          momentId: momentId, //被关注人的id
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          console.log('新增收藏', res)
          wx.showToast({
            title: '收藏成功',
            image: '../../assets/success.png',
            duration: 1000,
          })
          this.setData({
            showCollect: false
          })
          this.collectList()
        }
      })
    }

  },
  // 删除关注收藏平台瞬间 
  collectNo() {
    var momentId = this.data.momentId
    if (app.checkHasLogin()) {
      var postObj = {
        url: `/mobileUser/collection/remove`,
        method: 'delete',
        data: {
          momentId: momentId
        }
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          console.log('删除关注', res)
          wx.showToast({
            title: '取消收藏',
            image: '../../assets/success.png',
            duration: 1000,
          })
          this.setData({
            showCollect: true
          })
          this.collectList()
        }
      })
    }
  },
  //举报
  jubao() {
    wx.showLoading({
      title: '举报中...',
      success: () => {
        setTimeout(() => {
          setTimeout(() => {
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '举报成功',
                  image: '../../assets/warning.png',
                  duration: 1000
                })
              },
            })
          }, 500)
        }, 500)
      }
    })

  },
  // 分享给好友
  shareAppMessage() {
    // wx.showShareMenu({
    //   withShareTicket: false,
    //   menus: ['shareAppMessage', 'shareTimeline']
    // })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    var momentId = options.momentId
    that.setData({
      momentId: momentId
    })
    // 获取文章信息
    that.getRich(momentId)
    //获取评论信息
    // that.getComment()
    //一进入页面检验点赞
    setTimeout(function () {
      if (app.globalData.hasLogin == true) {

        var postObj = {
          url: `/mobileUser/parise/list`,
          method: 'get',
          data: {
            momentId: that.data.momentId
          }
        }
        app.request.wxRequest(postObj).then(res => {
          if (res.data.code === 200) {
            console.log('检验是否点赞', res)
            if (res.data.data.momentList.length == 0) {
              that.setData({
                buttonType: 'default'
              })
            } else {
              that.setData({
                buttonType: 'info'
              })
            }
          }
        })

        that.checkcommentListZan()
        // 获取关注列表
        // that.followList()
      }

    }, 200)




    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    // that.getRich()
    if (!!that.data.momentId) {
      that.getRich(that.data.momentId)
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})